package cn.ibdsr.human.service.impl;

import cn.ibdsr.human.constant.*;
import cn.ibdsr.human.db.mapper.CompanyMapper;
import cn.ibdsr.human.db.mapper.ServerInitMapper;
import cn.ibdsr.human.db.mapper.UserMapper;
import cn.ibdsr.human.db.model.*;
import cn.ibdsr.human.exception.BizExceptionEnum;
import cn.ibdsr.human.exception.BusinessException;
import cn.ibdsr.human.manager.LogFormatManager;
import cn.ibdsr.human.service.CompanyService;
import cn.ibdsr.human.transfer.UserDetailDTO;
import cn.ibdsr.human.transfer.company.*;
import cn.ibdsr.human.transfer.platform.CompanyQueryDTO;
import cn.ibdsr.human.transfer.platform.UserListDetailDTO;
import cn.ibdsr.human.transfer.platform.UserListResponseDTO;
import cn.ibdsr.human.util.MybatisPlusPage;
import cn.ibdsr.human.warpper.CompanyResponseWarpper;
import cn.ibdsr.human.warpper.UserDetailWarpper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CompanyServiceImpl implements CompanyService {
    @Resource
    private LogFormatManager logFormatManager;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ServerInitMapper serverInitMapper;
//    @Override
//    public String generateCode() {
//        Long maxId = companyMapper.getMaxId();
//        if (StringUtils.isEmpty(maxId)) {
//            maxId = 0L;
//        }
//        return String.valueOf(BizConstants.BASE_CODE + maxId + 1);
//    }

    /**
     * 生成code
     *
     * @return
     */
    @Override
    public String generateCode() {
        QueryWrapper<ServerInit> serverInitQueryWrapper = new QueryWrapper<>();
        serverInitQueryWrapper.eq("type", String.valueOf(ServerInitEnum.CODE_LENGTH.getType()));
        ServerInit serverInit = serverInitMapper.selectOne(serverInitQueryWrapper);
        if (serverInit == null) {
            throw new BusinessException(BizExceptionEnum.SERVIER_INIT_CODE_ERROR);
        }
        Integer length = Integer.valueOf(serverInit.getConfigValue());
        if (length < 6) {
            length = 6;
        }
        if (length > 8)
            length = 8;
        Long base_value = 100000L;
        switch (length) {
            case 7:
                base_value = 1000000L;
                break;
            case 8:
                base_value = 10000000L;
                break;
            default:
                break;
        }
        String code = "";
        while (true) {
            code = String.valueOf((long) ((Math.random() * 9 + 1) * base_value));
            if(!checkCodeExist(code,null)){
              break;
            }
        }
        return code;
    }

    /**
     * 企业获取自己的信息
     * @param userId
     * @return
     */
    @Override
    public CompanyResponseDTO getCompanyInformation(Long userId) {

        CompanyResponseDTO companyResponseDTO = new CompanyResponseDTO();
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        if (user.getCompanyId() == null) {
            companyResponseDTO.setStatus(CompanyStatusEnum.NO_SUBMIT.getType());
            companyResponseDTO.setStatusDes(CompanyStatusEnum.NO_SUBMIT.getDesc());
            return companyResponseDTO;
        } else {
            Company company = companyMapper.selectById(user.getCompanyId());
            if (company == null) {
                companyResponseDTO.setStatus(CompanyStatusEnum.NO_SUBMIT.getType());
                companyResponseDTO.setStatusDes(CompanyStatusEnum.NO_SUBMIT.getDesc());
                return companyResponseDTO;
            }
            JSONObject jsonObject = (JSONObject) (new CompanyResponseWarpper(JSONObject.parseObject(JSONObject.toJSONString(company)),true)).warp();
            companyResponseDTO = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), CompanyResponseDTO.class);
            companyResponseDTO.setStatus(CompanyStatusEnum.valueOf(company.getStatus()).getType());
            companyResponseDTO.setStatusDes(CompanyStatusEnum.valueOf(company.getStatus()).getDesc());
        }
        companyResponseDTO.setUserPhone(user.getAccount());
        return companyResponseDTO;
    }
    /**
     * 平台获取企业信息
     * @param id
     * @return
     */
    @Override
    public CompanyResponseDTO platFormGetCompanyInformation(Long id) {
        CompanyResponseDTO companyResponseDTO = new CompanyResponseDTO();

        Company company = companyMapper.selectById(id);
        if (company == null) {
            companyResponseDTO.setStatus(CompanyStatusEnum.NO_SUBMIT.getType());
            companyResponseDTO.setStatusDes(CompanyStatusEnum.NO_SUBMIT.getDesc());
            return companyResponseDTO;
        }
        JSONObject jsonObject = (JSONObject) (new CompanyResponseWarpper(JSONObject.parseObject(JSONObject.toJSONString(company)),true)).warp();
        companyResponseDTO = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), CompanyResponseDTO.class);
        companyResponseDTO.setStatus(CompanyStatusEnum.valueOf(company.getStatus()).getType());
        companyResponseDTO.setStatusDes(CompanyStatusEnum.valueOf(company.getStatus()).getDesc());

        return companyResponseDTO;
    }

    /**
     * 企业保存信息
     *
     * @param userId
     * @param companySaveDTO
     * @return
     */
    @Override
    public Long save(Long userId, CompanySaveDTO companySaveDTO) {
        User user = userMapper.selectById(userId);
        if (user == null || !user.getSysType().equals(PlatformEnum.COMPANY.getCode())) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        Company company = null;
        if (user.getCompanyId() == null) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        company = companyMapper.selectById(user.getCompanyId());
        if (company == null) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        Company companyTemp = new Company();
        companyTemp = JSONObject.parseObject(JSONObject.toJSONString(companySaveDTO), Company.class);
        companyTemp.setId(company.getId());
        String outerName=getOuterName(companyTemp.getName());
        companyTemp.setOuterName(outerName);
        companyTemp.updateById();
        return companyTemp.getId();
    }

    /**
     * 获取企业外部名字
     *
     * @param name
     * @return
     */
    private String getOuterName(String name) {
        int baseLenth = 4;
        int nameLength = name.length();
        if (nameLength >= 8) {
        } else if (nameLength >= 6) {
            baseLenth = 2;
        } else if (nameLength >= 4) {
            baseLenth = 1;
        } else if (nameLength >= 2) {
            baseLenth = 0;
        }
        if (nameLength >= 2) {
            String newName = "";
            for (int i = 0; i < name.length(); i++) {
                if (i > 0 && i < name.length() - baseLenth) {
                    newName += "*";
                } else {
                    newName += name.charAt(i);
                }
            }
            return newName;
        } else {
            throw new BusinessException(BizExceptionEnum.COMPANY_NAME_WRONG);
        }

    }

    /**
     * 撤销认证和重新提交认证
     *
     * @param userId
     * @param companyStatusDTO
     * @return
     */
    @Override
    public Long saveCompanyStatus(Long userId, CompanyStatusDTO companyStatusDTO) {
        User user = userMapper.selectById(userId);
        if (user == null || !user.getSysType().equals(PlatformEnum.COMPANY.getCode())) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        Company company = companyMapper.selectById(user.getCompanyId());
        if (company == null) {
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_EXISTED);
        }

        if (companyStatusDTO.getStatus().equals(CompanyStatusEnum.NO_SUBMIT.getType())) {
            //如果是撤销认证请求
            //原来应该处于待认证状态
            if (!company.getStatus().equals(CompanyStatusEnum.WATING.getType())) {
                throw new BusinessException(BizExceptionEnum.COMPANY_NOT_WAITING_FOR_IDENTIFICATION);
            }
            company.setStatus(CompanyStatusEnum.NO_SUBMIT.getType());
            company.setUpdateTime(LocalDateTime.now());
            company.updateById();
            return company.getId();
        } else if (companyStatusDTO.getStatus().equals(CompanyStatusEnum.WATING.getType())) {
            // 如果是重新提交认证请求
            //原来不能处于未认证状态

            company.setStatus(CompanyStatusEnum.WATING.getType());
            company.setUpdateTime(LocalDateTime.now());
            company.updateById();
            return company.getId();
        } else {

            throw new BusinessException(BizExceptionEnum.REQUEST_PARAM_IS_ERROR);

        }

    }

    /**
     * 创建公司信息
     * @return
     */
    @Override
    public Company createCompany( ) {
        Company company = new Company();
        company.setCode(generateCode());
        companyMapper.insert(company);
        return company;
    }

    /**
     *      * 企业修改联系人
     * @param userId
     * @param updateConnectUserDTO
     * @return
     */
    @Override
    public Long updateConnectUser(Long userId, UpdateConnectUserDTO updateConnectUserDTO) {
        User user = userMapper.selectById(userId);
        if (user == null || !user.getSysType().equals(PlatformEnum.COMPANY.getCode())) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        Company company = companyMapper.selectById(user.getCompanyId());
        if (company == null) {
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_EXISTED);
        }
        company.setContactName(updateConnectUserDTO.getContactName());
        company.setContactJob(updateConnectUserDTO.getContactJob());
        company.setContactPhone(updateConnectUserDTO.getContactPhone());
        company.setUpdateTime(LocalDateTime.now());
        company.setUpdateUser(userId);
        companyMapper.updateById(company);
        return company.getId();
    }

    /**
     * 计算企业的岗位数量
     *
     * @param companyId
     * @param userId
     */
    @Override
    public void computerJobCnt(Long companyId, Long userId, Boolean isAdd) {
        Company company = companyMapper.selectById(companyId);
        if (company == null) {
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_EXISTED);
        }
        Integer jobCount = company.getJobCnt();
        if (isAdd) {
            jobCount++;
        } else {
            jobCount--;
        }
        Company companyTemp=new Company();
        companyTemp.setId(companyId);
        jobCount = jobCount >= 0 ? jobCount : 0;
        companyTemp.setUpdateTime(LocalDateTime.now());
        companyTemp.setUpdateUser(userId);
        companyTemp.setJobCnt(jobCount);
        companyMapper.updateById(companyTemp);
        logFormatManager.formatKeyPointLog("计算企业的岗位数量",JSONObject.toJSONString(company),BizConstants.MODULE_COMPANY);

    }

    /**
     * 分页获取企业信息
     *
     * @param companyQueryDTO
     * @return
     */
    @Override
    public CompanyListDTO getCompanies(CompanyQueryDTO companyQueryDTO) {

        if (companyQueryDTO.getPageNo() == null || companyQueryDTO.getPageNo() <= 0) {
            companyQueryDTO.setPageNo(1L);
        }
        if (companyQueryDTO.getPageSize() == null || companyQueryDTO.getPageSize() <= 0) {
            companyQueryDTO.setPageSize(BizConstants.DEFAULT_PAGE_SIZE);
        } else if (companyQueryDTO.getPageSize() > BizConstants.MAX_PAGE_SIZE) {
            throw new BusinessException(BizExceptionEnum.REQUEST_ERROR);
        }
        Page<CompanyResponseDTO> page = MybatisPlusPage.defaultNewPage(companyQueryDTO);
        List<CompanyResponseDTO> companies = userMapper.listCompaniesByPage(page,
                companyQueryDTO.getUserPhone(),
                companyQueryDTO.getCode(),
                companyQueryDTO.getName(),
                companyQueryDTO.getCreditCode(),
                companyQueryDTO.getProper(),
                companyQueryDTO.getStatus()
        );
        List<CompanyResponseDTO> companiesNew=new ArrayList<>();
        // 创建返回结果
        Long pageIdex = page.getSize() * (page.getCurrent() - 1);
        for (CompanyResponseDTO company : companies) {
            pageIdex++;
            JSONObject jsonObject = (JSONObject) (new CompanyResponseWarpper(JSONObject.parseObject(JSONObject.toJSONString(company)),true)).warp();
            company = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), CompanyResponseDTO.class);
            if(company.getStatus()!=null){
                company.setStatusDes(CompanyStatusEnum.valueOf(company.getStatus()).getDesc());
            }else {
                company.setStatusDes(CompanyStatusEnum.NO_SUBMIT.getDesc());
            }
            company.setRank(pageIdex);
            companiesNew.add(company);
        }
        page.setRecords(companiesNew);
        CompanyListDTO companyListDTO = new CompanyListDTO();
        companyListDTO.setPageNo(page.getCurrent());
        companyListDTO.setPageSize(page.getSize());
        companyListDTO.setTotalPage(page.getPages());
        companyListDTO.setTotalCount(page.getTotal());
        companyListDTO.setData(page.getRecords());
        return companyListDTO;
    }



    /**
     * 平台认证企业
     * @param userId
     * @param companySaveDTO
     * @return
     */
    @Override
    public Long identifyCompany(Long userId, PlatfromIdentifyCompanyDTO companySaveDTO) {
        //如果认证失败，必须填写失败原因
        if(companySaveDTO.getStatus().equals(CompanyStatusEnum.FAIL.getType())){
            if(StringUtils.isEmpty(companySaveDTO.getReviewRemark())){
                throw new BusinessException(BizExceptionEnum.REVIEW_TIP_NOT_EXISTED);
            }
        }
        return saveCompanyInfromation(userId,companySaveDTO,true);
    }

    /**
     * 平台编辑企业信息
     * @param userId
     * @param companySaveDTO
     * @return
     */
    @Override
    public Long platformSaveCompany(Long userId, PlatfromIdentifyCompanyDTO companySaveDTO) {
        return saveCompanyInfromation(userId,companySaveDTO,false);
    }

    /**
     * 保存企业信息
     * @param companySaveDTO
     * @return
     */
    private Long saveCompanyInfromation(Long userId,PlatfromIdentifyCompanyDTO companySaveDTO,Boolean identify){

        Company company = companyMapper.selectById(companySaveDTO.getId());
        if (company == null) {
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_EXISTED);
        }
        if(identify&&!company.getStatus().equals(CompanyStatusEnum.WATING.getType())){
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_APPLY_IDENTIFY);
        }
        if(checkCodeExist(companySaveDTO.getCode(),company.getId())){
            throw new BusinessException(BizExceptionEnum.CODE_ERROR);
        }
        Company companyTemp = new Company();
        companyTemp = JSONObject.parseObject(JSONObject.toJSONString(companySaveDTO), Company.class);
        companyTemp.setId(company.getId());
        companyTemp.setUpdateUser(userId);
        companyTemp.setUpdateTime(LocalDateTime.now());
        companyTemp.updateById();
        return companyTemp.getId();
    }

    /**
     * 检查编码存在
     * @param code
     * @return
     */
    private boolean  checkCodeExist(String code,Long companyId){
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        if(companyId!=null){
            queryWrapper.ne("id", companyId);
        }
        Company company = companyMapper.selectOne(queryWrapper);
        if (company != null) {
            return true;
        }
        return false;
    }
}
